<script lang="ts">
export default {
  name: 'subuserList',
  description: '企业子用户管理',
};
</script>
<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import examineList from './examineList.vue';
import { Search, Plus, Edit, Refresh, Delete } from '@element-plus/icons-vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { SubuserType, SubuserTypeQuery } from '@/api/occupant/subuser/types';
import {
  casualCheckPages
} from '@/api/system/examine/index';
import {
  casualEntrepreneurItempages,
  casualEntrepreneurAddItem,
  casualEntrepreneurUpdateItem,
  casualEntrepreneurDelitem
} from '@/api/occupant/subuser';
import { casualEntrepreneurOptions } from '@/api/occupant/enterprise';
import { number } from 'vue-types';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: false,
  // 选中ID数组
  ids: [],
  deptOptions: [],
  dialog: {
    title: '',
    visible: false,
  },
  shidlo:'',
  dialogHS: {
    title: '',
    visible: false,
  },
  dataList: [] as SubuserType[],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as SubuserTypeQuery,
  formData: {} as SubuserType,
  rules: {
    entrepreneurId: [{ required: true, message: '请选择企业用户', trigger: 'blur' }],
    accountName: [
      { required: true, message: '请填写账户名称', trigger: 'blur' },
    ],
    nickname: [
      { required: true, message: '请填写昵称', trigger: 'blur' },
    ]
  },
  bigList:[],
  total: 0,
  casualEntrepreneurOption: [] as OptionType[],
});

const {
  ids,
  loading,
  dataList,
  queryParams,
  formData,
  rules,
  dialog,
  shidlo,
  dialogHS,
  total,
  bigList,
  casualEntrepreneurOption
} = toRefs(state);
function getOptions() {
  casualEntrepreneurOptions().then((res) => {
    casualEntrepreneurOption.value = res.data;
  });
}
function principalAccount(id:string | number){
  return bigList.value.some((item:any)=>{
    return item.principalAccount == id
  })

}
function handleQuery() {
  loading.value = true;
  casualEntrepreneurItempages(state.queryParams).then(({ data }) => {
    dataList.value = data.list as any;
    total.value = data.total;
    loading.value = false;
  });
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
}

/**
 * 重置
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**
 * 添加
 */
function handleAdd(row: any) {
  dialog.value = {
    title: '添加个人用户',
    visible: true,
  };
}

/**
 * 修改
 */
async function handleUpdate(row: any) {
  state.formData = row;
  state.formData.password = ''
  state.dialog = {
    title: '修改个人用户',
    visible: true,
  };
}

function handleupdatePassword(row: { [key: string]: any }) {
  ElMessageBox.prompt(
    '请输入用户「' + row.accountName + '」的新密码',
    '重置密码',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  )
    .then(({ value }) => {
      if (!value) {
        ElMessage.warning('请输入新密码');
        return false;
      }
      let reg =  /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$/
      if (!reg.test(value)) {
        ElMessage.warning('密码由8位数字、大小写字母和特殊符号组成!');
        return false
      }
      casualEntrepreneurUpdateItem({id:row.id,password:value}).then(() => {
        ElMessage.success('密码重置成功，新密码是：' + value);
      });
    })
    .catch(() => {});
}
/**
 * 删除
 */
function handleDelete(row: any) {
  const ids = [row.id || state.ids].join(',');
  if (!ids) {
    ElMessage.warning('请勾选删除项');
    return;
  }
  ElMessageBox.confirm(`确认删除已选中的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      casualEntrepreneurDelitem(ids).then(()=>{
        ElMessage.success('删除成功');
        resetQuery()
      })
    })
    .catch(() => ElMessage.info('已取消删除'));
}
function handleHS(row:any){
  console.log(row.id);

  state.shidlo = row.id
  state.dialogHS = {
    visible:true,
    title:'审核配置'
  }
}
function closeDialogHS(row:any){
  state.dialogHS = {
    visible:false,
    title:''
  }
}
/**
 * 确认
 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      let parmas = Object.assign({}, formData.value);
      if (formData.value.id) {
       casualEntrepreneurUpdateItem(parmas).then(() => {
         ElMessage.success('编辑成功');
         closeDialog();
         resetQuery();
       });
      } else {
        casualEntrepreneurAddItem(parmas).then(() => {
         ElMessage.success('新增成功');
         closeDialog();
         resetQuery();
       });
      }
    }
  });
}
/**
 * 关闭弹窗
 **/
function closeDialog() {
  dialog.value.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

onMounted(() => {
  handleQuery();
  getOptions();
  casualCheckPages({pageSize:100,pageNum:1}).then((res:any)=>{
    state.bigList = res.data.list
  })
});
</script>
<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="queryParams.accountName" placeholder="请输入账户名称" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" :icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="resetQuery"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card>
      <!--toolbar-->
      <template #header>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
      </template>

      <!--table-->
      <el-table v-loading="loading" :data="dataList" row-key="id" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="entrepreneurName" label="企业用户" width="140" />
        <el-table-column prop="accountName" label="账户名称" width="140" />
        <el-table-column prop="nickname" label="昵称" width="140" />
        <el-table-column prop="nickname" label="是否已配置审核" width="140" >
          <template #default="scope">
            <span>{{ principalAccount(scope.row.id)?'是':'否'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="是否主账号" width="140" >
          <template #default="scope">
            <span>{{ scope.row.isMain == '1'?'是':'否' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleupdatePassword(scope.row)">
              重置密码
            </el-button>
            <el-button type="success" link @click.stop="handleUpdate(scope.row)">
              编辑
            </el-button>

            <el-button type="danger" :disabled='scope.row.isMain == "1"' link @click.stop="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button type="primary" link @click.stop="handleHS(scope.row)">
              添加审核配置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- pagination -->
      <pagination v-if="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>
  </div>

  <!-- dialog -->
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" @close="closeDialog">
    <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="企业用户" prop="entrepreneurId">
        <el-select v-model="formData.entrepreneurId" placeholder="请选择企业用户">
          <el-option v-for="item in casualEntrepreneurOption" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="账户名称" prop="accountName">
        <el-input v-model="formData.accountName" placeholder="请填写账户名称"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请填写昵称"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-if="dialogHS.visible" :title="dialogHS.title" v-model="dialogHS.visible" width="80%" @close="closeDialogHS">
    <examine-list :shidlo='shidlo'></examine-list>
  </el-dialog>
</template>

<style scoped>
</style>
